import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { useRouter } from 'vue-router'; // 引入 useRouter
import { UsersApi } from '../api/index.js';
import { ResponseStatus } from '../api/enums.js'
import { MessageBox } from '../components/dialog/MessageBox.js';
export const useUserStore = defineStore('user', () => {
    //定义一个请求状态变量
    const requesting = ref(false)
    // 定义一个响应式变量 username
    const username = ref('aaa')
    // 定义一个响应式变量 登录状态
    const isLogin = ref(true)
    // 定一个令牌字符串 token
    const token = ref('2vxhjn2g7zwcc9v3uzdx3o')
    const router = useRouter(); // 获取路由实例

    /**
     * 用户注册函数
     * @param userName
     * @param password
     * @returns
     */
    async function register(userName: string, password: string) {
        // 注册
        try {
            let res: ResponseObject<User> = await UsersApi.register({
                username: userName,
                password: password
            })
            MessageBox.alert('注册成功,请登录!');
            router.push('/login');
        } catch (error) {

        }
    }

    /**
     * 用户登录
     * @param userName 
     * @param password 
     * @param path 
     * @returns 
     */

    async function login(userName: string, password: string, path = '/') {
        // 登录
        let res: ResponseObject<User> = await UsersApi.login(userName, password)
        if (res.status !== ResponseStatus.success) {
            throw res.message
        }
        username.value = res.data.userName
        token.value = res.data.token??''
        isLogin.value = true
        if (!!path) {
            // 导航到默认首页
            router.push(path);
        }
        return res
    }

    async function logout(path = '/login') {
        // 退出登录
        let res: ResponseObject<any> = await UsersApi.logout()
        if (res.status !== ResponseStatus.success) {
            throw res.message
        }
        username.value = ''
        token.value = ''
        isLogin.value = false
        // 导航到登录页
        if (!!path) {
            // 导航到默认首页
            router.push(path);
        }
    }

    return { requesting, username, isLogin, token, register, login, logout }
})
